package com.etymgiko.spaceshipshop.web;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etymgiko.spaceshipshop.service.SpaceShipManager;
import com.etymgiko.spaceshipshop.model.SpaceShip;
import com.etymgiko.spaceshipshop.Constants;

import java.util.List;

/**
 * Processes available ships.
 *
 * @author Ivan Holub
 */
public class AvailableShipsAction extends Action {

    /**
     * Number of elements in page.
     */
    private static final int PAGE_SIZE = Constants.PAGE_SIZE;

    private SpaceShipManager spaceShipManager;

    public void setSpaceShipManager(SpaceShipManager spaceShipManager) {
        this.spaceShipManager = spaceShipManager;
    }

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

        HiddenForm hiddenForm = (HiddenForm) form;

        String filter = null;
        int pageNumber = 1;
        if (hiddenForm.isActionSearch()) {
            // User pressed search button.
            String searchParam = hiddenForm.getSearch();
            request.setAttribute("searchOld", searchParam);
            filter = searchParam;
        } else if (hiddenForm.isActionPage()) {
            // User clicked page navigation link.
            String searchOldParam = hiddenForm.getSearchOld();
            request.setAttribute("searchOld", searchOldParam);
            filter = searchOldParam;
            pageNumber = hiddenForm.getPage();
        }

        request.setAttribute("currentPageNumber", pageNumber);

        long count = spaceShipManager.findSpaceShipsCount(null, filter);
        List<SpaceShip> list = spaceShipManager.findSpaceShips(null, filter, pageNumber);
        int numberOfPages = (int)((count + PAGE_SIZE - 1) / PAGE_SIZE);

        request.setAttribute("numberOfPages", numberOfPages);
        request.setAttribute("spaceShips", list);

        return mapping.findForward("success");
    }
}
